﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using PeaceBlogData;
using PeaceBlogData.Tables;

namespace PeaceBlog.Controllers.API
{
    public class CategoriesController : ApiController
    {
        private PeaceBlogEntity db = new PeaceBlogEntity();

        // GET: api/Categories
        [HttpGet]
        public async Task<List<Categories>> GetCategories()
        {
            return await db.GetAllCategoriesAsync();
        }

        // GET: api/Categories/5
        [HttpGet]
        public async Task<IHttpActionResult> GetCategories(int id)
        {
            var category = await db.GetCategory(id);
            if (category == null)
                return NotFound();
            return Ok(category);
        }

        [HttpPost]
        public async Task<Categories> GetCategory(int Id)
        {
            var categories = await db.GetCategory(Id);
            if (categories == null)
                return null;

            return categories;
        }

        // PUT: api/Categories/
        [HttpPut]
        public async Task<IHttpActionResult> UpdateCategory(Categories category)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                await db.UpdateCategory(category);
            }
            catch (DbUpdateConcurrencyException)
            {
                return NotFound();
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Categories
        [HttpPost]
        public async Task<IHttpActionResult> PostCategories(Categories category)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);
            try
            {
                await db.AddCategory(category);
            }
            catch
            {
                return BadRequest("Kategori Eklenemedi!");
            }

            return Ok(category);
        }

        // DELETE: api/Categories/5
        [HttpDelete]
        public async Task<IHttpActionResult> DeleteCategories(int CategoryID)
        {
            try
            {
                await db.DeleteCategory(CategoryID);
                return Ok("Kategori Silindi!");
            }
            catch
            {
                return NotFound();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}